from services import SparkApi
from services.Privacy import Privacy


# 用于配置大模型版本，默认“general/generalv2”
# domain = "general"  # v1.5版本
domain = "generalv2"    # v2.0版本
# 云端环境的服务地址
# Spark_url = "ws://spark-api.xf-yun.com/v1.1/chat"  # v1.5环境的地址
Spark_url = "ws://spark-api.xf-yun.com/v2.1/chat"  # v2.0环境的地址


conversations = []


# length = 0

def buildConversations(role, content):
    jsonContent = {"role": role, "content": content}
    conversations.append(jsonContent)
    return conversations


def getLength(text):
    """
    计算会话中总字数
    :param text: 会话列表
    :return: 总字数
    """
    length = 0
    for content in text:
        temp = content["content"]
        contentLength = len(temp)
        length += contentLength
    return length


def checkLength(text):
    """
    控制会话总字数小于等于8000，超过的话就删除会话记录中最早的一条，直到满足字数要求。
    :param text: 会话列表
    :return: 总字数小于等于8000的会话列表
    """
    while getLength(text) > 8000:
        del text[0]
    return text


if __name__ == '__main__':
    conversations.clear()
    while 1:
        Input = input("\n" + "我:")
        question = checkLength(buildConversations("user", Input))
        SparkApi.answer = ""
        print("星火:", end="")
        answer = SparkApi.main(
            Privacy.SPARK_APP_ID.value, Privacy.SPARK_API_KEY.value, Privacy.SPARK_API_SECRET.value,
            Spark_url, domain, question
        )
        buildConversations("assistant", answer)
        # print(str(text))
